package net.htjs.juc.supersedeprint;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class WaitNotifyPrint {

    public static void main(String[] args) {
        WaitNotify waitNotify = new WaitNotify(1, 10);
        new Thread(() -> waitNotify.print("A", 1, 2)).start();
        new Thread(() -> waitNotify.print("B", 2, 3)).start();
        new Thread(() -> waitNotify.print("C", 3, 1)).start();
    }

    static class WaitNotify {

        private int flag;
        private int loopNumber;

        public WaitNotify(int flag, int loopNumber) {
            this.flag = flag;
            this.loopNumber = loopNumber;
        }

        public void print(String str, int waitFlag, int nextFlag) {
            for(int i = 0; i < loopNumber; i++) {
                synchronized (this) {
                    while(waitFlag != this.flag) {
                        try {
                            this.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    log.info(str);
                    this.flag = nextFlag;
                    this.notifyAll();
                }
            }
        }
    }
}
